import { _decorator, Component, Label, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Timer')
export class Timer extends Component {
    timer: number = 0;
    time: number = 0;
    state: number = 0;

    endCb: Function = null;
    label: Label = null;

    protected onLoad(): void {
        this.label = this.node.getComponent(Label);
    }

    protected start(): void {
    }

    StartCounter(second: number = 35, endCb: Function = null) {
        clearInterval(this.timer);
        this.endCb = endCb;
        this.time = second;
        this.timer = setInterval(this.Counter.bind(this), 1000);
    }

    PauseCounter() {
        clearInterval(this.timer);
    }

    ResumeCounter() {
        this.timer = setInterval(this.Counter.bind(this), 1000);
    }

    StopCounter() {
        this.endCb = null;
        clearInterval(this.timer);
    }

    Counter() {
        this.time -= 1;
        let hour_0 = this.time / 60 / 60 / 10 < 0 ? 0 : Math.floor(this.time / 60 / 60 / 10);
        let hour_1 = this.time / 60 / 60 % 10 < 0 ? 0 : Math.floor(this.time / 60 / 60 % 10);
        let min_0 = this.time / 60 % 60 / 10 < 0 ? 0 : Math.floor(this.time / 60 % 60 / 10);
        let min_1 = this.time / 60 % 10 < 0 ? 0 : Math.floor(this.time / 60 % 10);
        let sec_0 = this.time % 60 / 10 < 0 ? 0 : Math.floor(this.time % 60 / 10);
        let sec_1 = this.time % 60 % 10;

        this.label.string = `${hour_0}${hour_1}:${min_0}${min_1}:${sec_0}${sec_1}`

        if (this.time <= 0) {
            this.endCb && this.endCb();
            clearInterval(this.timer);
        }
    }
}


